<template>
  <UploadExcel :on-success="handleSuccess" :befor-upload="beforUpload" />
</template>

<script>
import { batchAddEmployeeApi } from '@/api/employees'
export default {
  name: 'Import',
  methods: {
    beforUpload(file) {
      const isLtim = file.size / 1024 / 1024 < 1 // 传入文件小于1M
      if (isLtim) {
        return true
      }
      this.$message({
        message: '不能上传大于1M的文件',
        type: 'warning'
      })
    },
    handleSuccess({ results, header }) {
      // results 存的是excel信息
      // header 存的是excel表头
      if (this.type === 'user') {
        this.batchAddEmployee(results)
      }
    },
    // 批量新增员工
    async batchAddEmployee(results) {
      // header中, results中的数据是中文的, 但是提交给后台的要是英文的
      const userRelations = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber'
      }
      const excelDate = []
      results.forEach(item => {
        const userInfo = {}
        for (const key in item) {
          const engLishKey = userRelations[key]
          if (['timeOfEntry', 'correctionTime'].includes(engLishKey)) {
            userInfo[engLishKey] = this.formatExcelDate(item[key])
          } else {
            userInfo[engLishKey] = item[key]
          }
        }
        excelDate.push(userInfo)
      })
      batchAddEmployeeApi(excelDate).then(res => {
        console.log(res)
        this.$message.success(res.data.message)
        this.$router.push('/employees/index')
      })
    },
    /**
     * 转换excel的日期格式
     * numb 时间戳
     * format 最后以什么形式连接
     */
    formatExcelDate(numb, format) {
      const time = new Date(numb * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return (
          year +
          format +
          (month < 10 ? '0' + month : month) +
          format +
          (date < 10 ? '0' + date : date)
        )
      }
      return year + '-' + (month < 10 ? '0' + month : month) + '-' + (date < 10 ? '0' + date : date)
    },
    computed: {
      // 返回地址?后面的type值
      type() {
        return this.$route.query.type
      }
    }
  }
}
</script>

<style>
</style>
